//
//  NSDate+Extension.swift
//  Hweibome
//
//  Created by 何川 on 15/12/13.
//  Copyright © 2015年 hechuan. All rights reserved.
//

import Foundation

extension NSDate {
    
    class func sinaDate(createStr: String)->NSDate? {
        let dt = NSDateFormatter()
        dt.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        dt.locale = NSLocale(localeIdentifier: "en_US")
        let createDate = dt.dateFromString(createStr)!
        //printLog(creatDate)
        return createDate
    }
    
    var sinaDateString: String {
        let dt = NSDateFormatter()
        dt.locale = NSLocale(localeIdentifier: "en_US")
        let calendar = NSCalendar.currentCalendar()

        if isThisYear(self) {
            dt.dateFormat = "是今年"
            
            if calendar.isDateInToday(self){
                //是今天
                let result = -self.timeIntervalSinceNow
                if result < 60 {
                    return "刚刚"
                }else if result < 60*60 {
                    return "\(Int(result)/60)分钟前"
                }else {
                    return "\(Int(result)/(60*60))小时前"
                }
            }else if calendar.isDateInYesterday(self){
                dt.dateFormat = "昨天 HH:mm"
            }else {
                dt.dateFormat = "MM-dd HH:mm"
            }
            
        }else
        {
            dt.dateFormat = "yyy-MM-dd HH:mm"
        }
        return dt.stringFromDate(self)
        
    }
    private func isThisYear(date: NSDate) -> Bool {
        let currentDate = NSDate()
        let dt = NSDateFormatter()
        dt.dateFormat = "yyyy"
        dt.locale = NSLocale(localeIdentifier: "en_US")
        let dateStr = dt.stringFromDate(currentDate)
        let currentDateStr = dt.stringFromDate(currentDate)
        
        return (dateStr as NSString).isEqualToString(currentDateStr)
    }
    
}